package org.brownflat.watergate.scm.svn;

import org.brownflat.watergate.scm.Revision;
import org.brownflat.watergate.scm.Revisions;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

/**
 * <p>&copy Rupert Jones 2011</p>
 *
 * @author rup
 */
public class SubversionRevisions implements Revisions {
    private List<Revision> subversionRevisions;
    private boolean empty;

    public SubversionRevisions(List<Revision> subversionRevisions) {
        List<Revision> input = new ArrayList<Revision>(subversionRevisions);
        Collections.sort(input, new Comparator<Revision>() {
            @Override
            public int compare(Revision one, Revision two) {
                if (one.getRevision() >= two.getRevision()) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
        this.subversionRevisions = input;
    }

    public boolean hasRevisionBefore(long revisionNumber) {
        return getRevisionBefore(revisionNumber) != null;
    }

    public Revision getRevisionBefore(long revisionNumber) {
        Revision lastSubversionRevision = null;
        for (Revision subversionRevision : subversionRevisions) {
            if (subversionRevision.getRevision() >= revisionNumber) {
                return lastSubversionRevision;
            }
            lastSubversionRevision = subversionRevision;
        }
        return lastSubversionRevision;
    }

    public Revision getRevision(long revision) {
        for (Revision thisSubversionRevision : subversionRevisions) {
            if (thisSubversionRevision.getRevision() == revision) {
                return thisSubversionRevision;
            }
        }
        return null;
    }

    public List<Revision> getRevisions() {
        return subversionRevisions;
    }

    public Revisions getRevisionsFromTo(long from, long to) {
        List<Revision> theseSubversionRevisions = new ArrayList<Revision>();

        for (Revision subversionRevision : subversionRevisions) {
            if (subversionRevision.getRevision() >= from && subversionRevision.getRevision() <= to) {
                theseSubversionRevisions.add(subversionRevision);
            }
        }
        return new SubversionRevisions(theseSubversionRevisions);
    }

    @Override
    public Iterator<Revision> iterator() {
        return subversionRevisions.iterator();
    }

    public int size() {
        if (subversionRevisions != null) {
            return subversionRevisions.size();
        } else {
            return 0;
        }
    }

    public boolean isEmpty() {
        return size() == 0;
    }

    public String toString() {
        return subversionRevisions.toString();
    }

    public Revision getFirstRevision() {
        if (!subversionRevisions.isEmpty()) {
            return subversionRevisions.get(0);
        }
        return null;
    }
}
